/**
 * Created by IntelliJ IDEA.
 * User: Slejus
 * Date: 13.10.29
 * Time: 14.48
 * To change this template use File | Settings | File Templates.
 */

var loadingMessage = {};

var waitLoading = function() {
    loadingMessage = Alfresco.util.PopupManager.displayMessage({
        displayTime: 0,
        effectDuration: 0.5,
        text: '<span class="wait">Kraunama, prašome palaukti...</span>',
        noEscape: true
    })
};

function getDocPreviewFormData(){
    var docPreviewForm = null;

    var postForms = $("form[method=post]");
    for (var i = 0; i < postForms.length; i++) {
        var pForm = postForms[i];
        var str = $(pForm).attr('id');
        if (str.indexOf("task-edit") >= 0) {
            var docPreviewFormId = $(pForm).attr('id');
            break;
        }
    }
    //var docPreviewFormId = $("form[method=post]").attr('id');
    if (docPreviewFormId) {
        docPreviewForm = Dom.get(docPreviewFormId);
    }
    if (docPreviewForm !== null) {
        var docPreviewFormData = {},
            length = docPreviewForm.elements.length;
        for (var i = 0; i < length; i++){
            var element = docPreviewForm.elements[i],
                name = element.name;
            if (name == "-" || element.disabled || element.type === "button") {
                continue;
            }
            if (name == undefined || name == "") {
                name = element.id;
            }
            var value = (element.type === "textarea") ? element.value : YAHOO.lang.trim(element.value);
            if (name) {
                // check whether the input element is an array value
                if ((name.length > 2) && (name.substring(name.length - 2) == '[]')) {
                    name = name.substring(0, name.length - 2);
                    if (docPreviewFormData[name] === undefined) {
                        docPreviewFormData[name] = new Array();
                    }
                    docPreviewFormData[name].push(value);
                }
                // check whether the input element is an object literal value
                else if (name.indexOf(".") > 0)
                {
                    var names = name.split(".");
                    var obj = docPreviewFormData;
                    var index;
                    for (var j = 0, k = names.length - 1; j < k; j++) {
                        index = names[j];
                        if (obj[index] === undefined) {
                            obj[index] = {};
                        }
                        obj = obj[index];
                    }
                    obj[names[j]] = value;
                }
                else if (!((element.type === "checkbox" || element.type === "radio") && !element.checked)) {
                    if (element.type == "select-multiple") {
                        for (var j = 0, jj = element.options.length; j < jj; j++) {
                            if (element.options[j].selected) {
                                if (docPreviewFormData[name] == undefined) {
                                    docPreviewFormData[name] = new Array();
                                }
                                docPreviewFormData[name].push(element.options[j].value);
                            }
                        }
                    }
                    else {
                        docPreviewFormData[name] = value;
                    }
                }
            }
        }
        return docPreviewFormData;
    }
}

var onDocPreviewLoaded = function(res) {
    loadingMessage.cancel();
    var htmlPreview = res.serverResponse.responseText;
    if (htmlPreview != null && htmlPreview != "" && htmlPreview != "undefined") {
        var docPreviewFormEl = Dom.get("dialog");
        docPreviewFormEl.innerHTML = htmlPreview;
        var options = {
            height: 860,
            width: 756,
            modal: true
        };
        $( "#dialog" ).dialog(options);
    }
};

var onDocPreviewFailureMessage = function(o) {
    loadingMessage.cancel();
    Alfresco.util.PopupManager.displayMessage({
        displayTime: 2,
        effectDuration: 0.5,
        text: 'Klaida bandant peržiūrėti formuojamą dokumentą.'
    });
};

function viewDocumentPreview(workflow, docType, tmpId) {
    waitLoading();
    var workflowDef = null;
    var postForms = $("form[method=post]");
    for (var i = 0; i < postForms.length; i++) {
        var pForm = postForms[i];
        var str = $(pForm).attr('action').split("/");
        if (str[6]) {
            if (str[6].indexOf("activiti") >= 0) {
                var workflowDef = str[6];
                break;
            }
        }
    }

    if (workflowDef == null) {
        Alfresco.util.PopupManager.displayPrompt(
        {
            title:"Klaida formuojant dokumentą",
            text: "Nenustatytas darbų sekos pavadinimas.",
            buttons:[
                {
                    text:Alfresco.util.message("Grįžti", this.name),
                    handler:function startDocument_back() {
                        this.destroy();
                    },
                    isDefault:true
                }
            ]
        });
        return false;
    }

    //var str = $("form[method=post]").attr('action').split("/");
    //var workflowDef = str[6]; console.log("WorkflowDef: " + workflowDef);
    var jsonData = getDocPreviewFormData();
    jsonData['workflow'] = workflow;
    jsonData['docType'] = docType;
    jsonData['tmpId'] = tmpId;

    Alfresco.util.Ajax.jsonRequest(
    {
        url: Alfresco.constants.PROXY_URI + "components/workflowdocpreview",
        method: "POST",
        dataObj: jsonData,
        successCallback:
        {
            fn: onDocPreviewLoaded,
            scope: this
        },
        failureCallback:
        {
            fn: onDocPreviewFailureMessage,
            scope: this
        },
        scope: this,
        execScripts: true
    });
}